<template>
	<view class="">
		<view class="s-input-wrap" style="margin:0">
			<view class="s-input-box flex-row">
				<text class="black-text">物料编号</text>
				<input @input="clearName" v-model="form.productNo" @confirm="inputProductNo" class="s-input flex1" placeholder="扫描 / 输入物料" />
				<image class="s-input-icon" src="/static/images/scan.png"></image>
			</view>
			<view class="s-input-box flex-row-between">
				<text class="black-text font-30">物料名称</text>
				<text class="black-text font-30">{{form && form.productName?form.productName:'---'}}</text>
			</view>
		</view>
		<view class="s-input-wrap" style="margin:25rpx 0 0">
			<view class="s-input-box flex-row">
				<text class="black-text">数量</text>
				<input type="number" v-model="form.quantity" @input="setNum" class="s-input flex1" placeholder="请输入数量" />
			</view>
		</view>
		<view class="content-list-total flex-row-between">
			<button @click="submit" class="botton p-botton botton-big">确定</button>
		</view>
	</view>
</template>

<script>
	import { validNum } from "@/utils/common"
	import { saveBarcode,getProductByNo } from "./api"
	var printModule = uni.requireNativePlugin("pda-print-PdaPrintModule")
	
	export default {
		data() {
			return {
				form:{
					productNo:'',
					quantity:''
				}
			}
		},
		methods:{
			// 验证大于等于1的整数
			setNum(e){
				if(e.target.value){
					let newValue = e.target.value.replace(/^\D*(\d*).*$/g, "$1")
					newValue = Math.max(1,newValue)
					this.$nextTick(()=>{
						this.form.quantity = newValue
					})
				}
			},
			inputProductNo(){
				// 根据物料编号获取物料
				getProductByNo(this.form.productNo).then(res=>{
					if(res.code == 200){
						if(!res.data){
							this.$modal.msgError("物料编号有误")
							this.$set(this.form,'productName','');
							return;
						}else{
							this.$set(this.form,'productName',res.data.productName);
						}
					}
				})
			},
			// 物料编号有变动时，需要把物料名称清除
			clearName(){
				this.$set(this.form,'productName','');
			},
			submit(){
				if (!this.form.productName) {
					this.$modal.msg("请输入物料编码")
				} else if (!this.form.quantity  || this.form.quantity ==0 ) {
					this.$modal.msg("请输入数量")
				} else{
					this.$modal.confirm('是否确认收货').then(() => {
						this.$modal.loading("收货中...")
						saveBarcode(this.form).then(res=>{
							this.$modal.closeLoading()
							console.log(res)
							if(res.code == 200){
								this.$modal.msgSuccess("收货成功")
								/** 打印完成后才能清除form表单数据，避免打印空值 **/ 
								printModule.printLabelAsync({
									'barcode': res.data.barCode,
									'title': res.data.barCode + '\n\n物料编号：'+ this.form.productNo + '\n数量：'+this.form.quantity,
									'distance': 500,
								},(ret) => {
									console.log(ret);
								});
								this.form = {
									productNo:'',
									quantity:''
								}
							} else {
								res.msg && this.$modal.confirmClose(res.msg)
							}
						})
					})
				}
			},
		}
	}
</script>

<style>
</style>
